use super::{
    err, err_value, json, ok, throw_err, Base, ECode, Fbf, Lock, Resp, SvCache, VBase, VMap, Value,
};

pub struct Setting;
pub struct Field;

impl Base for Setting {}
impl Base for Field {}

impl Setting {
    pub async fn do_cmd(&self, _data: &Value, cmd: &str, cache: SvCache, lock: Lock) -> Resp {
        let reader = Fbf;

        match cmd {
            "get" => {
                let _ = lock.lock().await;
                let ret = reader.get_file("", "", "setting", &cache)?;

                ok!(ret)
            }
            _ => throw_err!(ECode::NoServe, "no setting serve"),
        }
    }
}

impl Field {
    pub async fn do_cmd(
        &self,
        para: &Value,
        cmd: &str,
        k: &str,
        cache: SvCache,
        lock: Lock,
    ) -> Resp {
        let reader = Fbf;
        let data = para.ckobj()?;

        let line = data.ck_str("line")?;

        match cmd {
            "listnocache" => {
                let _ = lock.lock().await;

                let ret = reader.get_file_nocache(line, "field", k)?;

                ok!(ret)
            }
            "mdnocache" => {
                let _ = lock.lock().await;

                let v = data.ck_val("v")?;
                let _ = reader.write_nocache(line, "field", k, v).await?;

                ok!()
            }
            "list" => {
                let _ = lock.lock().await;

                let ret = reader.get_file(line, "field", k, &cache)?;

                ok!(ret)
            }
            "md" => {
                let _ = lock.lock().await;

                let v = data.ck_val("v")?;
                let _ = reader.write(line, "field", k, v, &cache).await?;

                ok!()
            }
            "rmfile" => {
                let _ = lock.lock().await;
                let _ = reader.remove(line, "field", k, &cache).await?;

                ok!()
            }
            _ => throw_err!(ECode::NoServe, "no field serve"),
        }
    }
}
